package com.mo.controller;


import com.mo.constants.RedisPrefix;
import com.mo.entity.Admin;
import com.mo.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author mo
 * @since 2022-08-27
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private IAdminService as;
    @Resource
    private RedisTemplate<String,Object>redisTemplate;

    @PostMapping("/tokens")
    public Map<String,String>tokens(@RequestBody Admin admin, HttpSession session){
       Map<String,String>map = new HashMap<>();
       String token = session.getId();
       //调用业务
        Admin admin1 =as.login(admin);
        //往redis里面放入数据
        redisTemplate.opsForValue().set(RedisPrefix.TOKEN+token,admin1,30, TimeUnit.MINUTES);
        map.put("token",token);
        return map;
    }
@DeleteMapping("/tokens/{token}")
    public void logout(@PathVariable String token){
        redisTemplate.delete(RedisPrefix.TOKEN+token);
}
    @GetMapping("/admin-user")
    public Map<String,String> userInfo(String token){
        Admin admin = (Admin)redisTemplate.opsForValue().get(RedisPrefix.TOKEN +token);
        Map<String,String> map = new HashMap<>();
        map.put("name",admin.getUsername());
        map.put("avatar",admin.getAvatar());
        return map;
    }
}

